﻿using System;
using System.Collections.Generic;
using System.Linq;
using WEB.BLL.Entities;
using WEB.BLL.Services;
using Ext.Net;
using WEB.Core.Util;
using WEB.Core.Controls;

namespace WEB.APP.Controls.List
{
    public partial class ProjectForm : BaseControl
    {
        public event EventHandler SaveClick;
        private void OnSaveClick()
        {
            if (SaveClick != null)
            {
                SaveClick(this, EventArgs.Empty);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (CurrentUser.RoleId == 2)
                tbStudent.Hidden = true;
        }

        protected override void CheckPer(bool Edit)
        {
            base.CheckPer(Edit);
            if (CurrentUser.RoleId == 2)
            {
                var _ett = ClientService.GetInstance().LoadByUsername(new ClientEntity() { Username = CurrentUser.UserName });
                cbClientID.Value = _ett.ClientId;
                tfClientName.Text = _ett.ClientName;
                cbClientID.Disabled = true;
            }
        }

        public void Show(decimal ProjectId)
        {
            try
            {
                var _ett = new ProjectEntity() { ProjectId = Convert.ToDecimal(ProjectId) };
                _ett = ProjectService.GetInstance().LoadPrimaryKeyEX(_ett);
                if (null == _ett)
                    return;
                FormPanel1.Reset();
                hfProjectId.Text = _ett.ProjectId.ToString();
                tfClientName.Text = _ett.ClientName;
                cbClientID.Value = _ett.ClientId;
                tfProjectName.Text = _ett.ProjectName;
                cbProjectType.Value = _ett.ProjectType;
                cbProjectSize.Value = _ett.ProjectSize;
                nfProjectYear.Value = _ett.ProjectYear;
                taProjectDesc.Text = _ett.ProjectDesc;
                if (!string.IsNullOrEmpty(_ett.OtherSkill))
                {
                    string _temp = "";
                    int _i = 1;
                    foreach (var item in _ett.OtherSkill.Split(','))
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            _temp += String.Format("{0}. {1}\n", _i, item.Trim());
                            _i++;
                        }
                    }
                    taOtherSkill.Text = _temp;
                }
                LoadExpertiseProject();
                LoadStudent();
                CheckPer(true);
                winDetails.Show();
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }

        [DirectMethod]
        public void LoadExpertiseProject()
        {
            try
            {
                ExpertiseProjectEntity ExpertiseProjectE = new ExpertiseProjectEntity()
                {
                    ProjectId = string.IsNullOrEmpty(hfProjectId.Text) ? 0 : Convert.ToDecimal(hfProjectId.Value)
                };
                IList<ExpertiseProjectEntity> _lst = ExpertiseProjectService.GetInstance().LoadByProjectId(ExpertiseProjectE);
                if (_lst == null)
                    return;
                storeExpertise.DataSource = _lst;
                storeExpertise.DataBind();
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }

        protected void LoadStudent()
        {
            try
            {
                tfProjectName.Disabled =
                    cbProjectType.Disabled =
                    cbProjectSize.Disabled =
                    nfProjectYear.Disabled =
                    taProjectDesc.Disabled =
                     Panel2.Disabled = false;
                grdExpertise.ColumnModel.SetEditable(1, true);
                if (string.IsNullOrEmpty(hfProjectId.Text))
                    return;
                IList<StudentEntity> _lst = StudentService.GetInstance().LoadByProject(new StudentEntity() { ProjectId = Convert.ToDecimal(hfProjectId.Value) });
                if (_lst == null)
                    return;
                stStudent.DataSource = _lst;
                stStudent.DataBind();
                if (_lst.Count > 0 && CurrentUser.RoleId == 2)
                {
                    tfProjectName.Disabled =
                        cbProjectType.Disabled =
                        cbProjectSize.Disabled =
                        nfProjectYear.Disabled =
                        taProjectDesc.Disabled =
                         Panel2.Disabled = true;
                    grdExpertise.ColumnModel.SetEditable(1, false);
                }
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }


        public void Show()
        {
            NewData();
            winDetails.Show();
        }

        protected void NewData()
        {
            hfProjectId.Text = string.Empty;
            FormPanel1.Reset();
            cbStudentID.Reset();
            LoadExpertiseProject();
            stStudent.RemoveAll();
            cbStudentID.Reset();
            CheckPer(false);
        }

        protected void btnNew_Click(object sender, DirectEventArgs e)
        {
            NewData();
            CheckPer(false);
        }

        protected ProjectEntity GetValueInEntity()
        {
            var _ett = new ProjectEntity()
            {
                ClientId = Convert.ToDecimal(cbClientID.Value),
                ProjectName = tfProjectName.Text,
                ProjectType = Convert.ToDecimal(cbProjectType.Value),
                ProjectSize = Convert.ToDecimal(cbProjectSize.Value),
                ProjectYear = Convert.ToDecimal(nfProjectYear.Value)
            };
            if (!string.IsNullOrEmpty(taProjectDesc.Text.Trim()))
                _ett.ProjectDesc = taProjectDesc.Text.Trim();

            if (!string.IsNullOrEmpty(taOtherSkill.Text.Trim()))
            {
                var _temp = "";
                foreach (var item in taOtherSkill.Text.Split('\n'))
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        _temp += item.Substring(item.IndexOf('.') + 1) + ", ";
                    }
                }
                _ett.OtherSkill = _temp.Remove(_temp.Length - 2);
            }
            return _ett;
        }

        [DirectMethod]
        public void SaveData(string jsonData1, string jsonData2)
        {
            try
            {
                List<ExpertiseProjectEntity> lstJson1 = new List<ExpertiseProjectEntity>();
                List<StudentEntity> lstJson2 = new List<StudentEntity>();
                lstJson1 = JSON.Deserialize<List<ExpertiseProjectEntity>>(jsonData1);
                lstJson2 = JSON.Deserialize<List<StudentEntity>>(jsonData2);

                var ProjectE = GetValueInEntity();

                ExpertiseProjectService ExpertiseProjectS = ExpertiseProjectService.GetInstance();
                StudentService StudentS = StudentService.GetInstance();
                if (!string.IsNullOrEmpty(hfProjectId.Text))
                {
                    ProjectE.ProjectId = Convert.ToDecimal(hfProjectId.Text);
                    ProjectService.GetInstance().Update(ProjectE);
                    foreach (var item in lstJson1)
                    {
                        item.ProjectId = ProjectE.ProjectId;
                        ExpertiseProjectS.InsertEX(item);
                    }
                    StudentS.DeleteProject(new StudentEntity() { ProjectId = ProjectE.ProjectId });
                }
                else
                {
                    ProjectE.ProjectId = 0;
                    ProjectService.GetInstance().Insert(ProjectE);
                    hfProjectId.Text = ProjectE.ProjectId.ToString();
                    foreach (var item in lstJson1)
                    {
                        if (!item.Checked)
                            continue;
                        item.ProjectId = ProjectE.ProjectId;
                        ExpertiseProjectS.Insert(item);
                    }
                }

                if (lstJson2 != null)
                {
                    foreach (var item in lstJson2)
                    {
                        item.ProjectId = ProjectE.ProjectId;
                        StudentS.UpdateProject(item);
                    }
                }
                cbStudentID.Reset();
                LoadStudent();

                Msg.Informational("Save data successful.");
                OnSaveClick();
                CheckPer(true);
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }
    }
}